import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 注册、登陆按钮状态
    btnMode: true,
    // router 导航守卫用于识别输入的号码是否存在token值
    telInput: '',
    shopsList: [],
    citysList: [],
    goodsMenu: [],
    // 当前定位数据
    nowPositong: {
      nowAddress: '定位中...',
      detailInfo: {},
      position: {}
    },
    // 手动更改的定位数据
    changePosition: {
      nowAddress: '定位中...',
      detailInfo: {},
      position: {}
    },
    // 手动定位和默认定位模式开关
    positionMode: false,
    // 订单列表详情
    listDetails: {},
    // 地址数据列表
    addressList: [],
    addID: 4,
    // 当前选中地址
    nowAddress: {},
    // 判断从 Address 组件返回 ViewOrder 还是 Account
    isForOrder: false,

    // <--- 当前所提交的订单数据 --->
    nowSubmitOrder: {},
    // 当前已支付订单
    nowOrderDetail: {},
    // 已支付订单列表
    orderAlreadypaid: [],
    // 历史订单数据
    historyOrderList: {},
    // 模拟当前已支付订单
    nowAlreadypaid: {},

    // <--- 账户相关数据 --->
    accountData: {
      // 余额
      remainingSum: 888.88,
      // 积分
      integral: 120,
      // 优惠券
      coupons: [],
      // 信用卡
      creditCard: [],
      // 个人资料
      personalData: {},
      // 收藏
      collection: []
    }
  },
  mutations: {
    // 注册、登陆按钮状态切换方法
    changeBtnMode(state) {
      state.btnMode = !state.btnMode
    },
    getInputTel(state, val) {
      state.telInput = val
    },
    // 初始化商家列表数据
    initShopsList(state, newList) {
      state.shopsList = newList
    },
    // 初始化全国城市列表数据
    initCityList(state, cityList) {
      state.citysList = cityList.city
    },
    // 初始化当前定位数据
    initPosition(state, nowAdd) {
      state.nowPositong = nowAdd
    },
    // 手动更改定位数据
    changePosition(state, newAdd) {
      state.changePosition = newAdd
    },
    // 手动更改定位数据的开关
    changePositionMode(state, mode) {
      state.positionMode = mode
    },
    // 初始化地址列表
    initAddressList(state, addList) {
      state.addressList = addList
    },
    // 更新、添加地址数据
    addAddress(state, newAdd) {
      // 模拟数据id的简单处理
      if (state.addressList.length === 0) {
        state.addID = 0
      }
      // 更改默认地址
      if (newAdd.isDefault === true) {
        state.addressList.some((o, k) => {
          if (o.isDefault === true) {
            state.addressList[k].isDefault = false
          }
        })
      }
      // 新增、更改逻辑
      if (newAdd.id !== undefined) {
        state.addressList.some((item, i) => {
          if (newAdd.id === item.id) {
            state.addressList[i] = newAdd
            return true
          }
        })
      } else {
        state.addID++
        newAdd.id = state.addID
        state.addressList.push(newAdd)
      }
    },
    // 删除地址数据
    sumAddress(state, newAdd) {
      state.addressList.some((item, i) => {
        if (newAdd.id === item.id) {
          state.addressList.splice(i, 1)
          return true
        }
      })
    },
    // 提交订单列表数据(购物车列表, 价格列表)
    submitGoodsList(state, list) {
      state.listDetails = list
    },
    // 从订单页面选择当前地址ID
    enterAddress(state, nowAddress) {
      state.nowAddress = nowAddress
    },
    // 改变 isForOrder 状态(控制地址组件返回order)
    changeIsForOrder(state, mode) {
      state.isForOrder = mode
    },
    // 提交当前订单
    submitOrder(state, orderData) {
      state.nowSubmitOrder = orderData
    },
    // 已下单订单
    sendPaidOrder(state, paidData) {
      // var item = JSON.parse(localStorage.getItem('orderAlreadypaid'))
      // if (item !== null) {
      //   state.orderAlreadypaid = item
      // }
      // 生成订单 0时区标准时间
      var orderTime = new Date().toISOString()
      var timestamp = Date.parse(orderTime)
      paidData.orderTime = orderTime
      paidData.timestamp = timestamp
      // 生成随机编号
      var arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
      var str = ''
      for (let i = 0; i < 12; i++) {
        var num = Math.round(Math.random() * (9 - 0) + 0)
        str += arr[num]
      }
      paidData.serialNum = str
      // 赋值id
      paidData.id = state.orderAlreadypaid.length
      // state.orderAlreadypaid.push(paidData)
      state.nowAlreadypaid = paidData
      // sessionStorage.setItem('orderAlreadypaid', JSON.stringify(state.orderAlreadypaid))
    },
    // 初始化历史订单
    initHistoryList(state, list) {
      state.historyOrderList = list
    },
    // 查看当前订单记录详情
    viewNowDetail(state, detail) {
      state.nowOrderDetail = detail
    }
  },
  actions: {
    // 初始化当前定位
    getNowPosition(content) {
      var _that = this
      AMap.plugin('AMap.Geolocation', function () {
        var geolocation = new AMap.Geolocation({
          // 是否使用高精度定位，默认：true
          enableHighAccuracy: true,
          // 设置定位超时时间，默认：无穷大
          timeout: 10000
        })
        geolocation.getCurrentPosition(function (status, result) {
          if (status === 'complete') {
            _that.lng = result.position.lng.toString()
            _that.lat = result.position.lat.toString()
            content.dispatch('getAddress', [(_that.lng + ',' + _that.lat).toString(), result.position])
          } else {
            // console.log('定位失败')
          }
        })
      })
    },
    // 根据坐标返回地址(逆地理编码，获取详细地址)
    getAddress(content, data) {
      axios({
        method: 'GET',
        url: 'https://restapi.amap.com/v3/geocode/regeo?parameters',
        params: {
          key: '8857783cc0db9ee595f99da7893d2e56',
          location: data[0]
        }
      }).then(result => {
        if (result.status === 200) {
          var address = result.data.regeocode.formatted_address
          var addressComponent = result.data.regeocode.addressComponent
          content.commit('initPosition', { nowAddress: address, detailInfo: addressComponent, position: data[1] })
        } else {
          content.commit('initPosition', { nowAddress: '定位失败,请刷新重试' })
        }
      })
    },
    // 获取商家列表
    getShopList(content) {
      axios.get('/static/StoreList.json').then(({ data }) => {
        content.commit('initShopsList', data)
      })
    },
    // 获取全国城市列表
    getCityList(content) {
      axios.get('/static/Address/AddList.json').then(({ data }) => {
        content.commit('initCityList', data)
      })
    },
    // 获取地址列表数据
    async getAddressList(content) {
      const { data: res } = await axios.get('/static/address/Address.json')
      content.commit('initAddressList', res.address)
    },
    // 请求历史订单记录
    async getHistoryOrder(content) {
      const { data: res } = await axios.get('/static/orders/transactions.json')
      content.commit('initHistoryList', res)
    }
  },
  getters: {
  },
  modules: {}
})
